﻿using MyWPF.Models;
using MyWPF.StaticData;
using MyWPF.Views.Others;
using NPOI.SS.Formula.Functions;
using Office;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;

namespace MyWPF.ViewModel.Subpage
{
    public class VM_JournalPage : BaseViewModel
    {
        public VM_JournalPage() 
        {
            
            #region 事件委托
            _openSetWindow = new DelegateCommand<object>(_OpenSetWindow);
            _refresh = new DelegateCommand<object>(_Refresh);
            _exportData = new DelegateCommand<object>(_ExportData);
            _firstPage = new DelegateCommand<object>(_FirstPage);
            _previousPage = new DelegateCommand<object>(_PreviousPage);
            _nextPage = new DelegateCommand<object>(_NextPage);
            _lastPage = new DelegateCommand<object>(_LastPage);
            _goTo = new DelegateCommand<object>(_GoTo);
            _loadedWindow = new DelegateCommand<object>(_LoadedWindow);
            _deleteSingleJournal = new DelegateCommand<object>(_DeleteSingleJournal);
            _deleteJournal = new DelegateCommand<object>(_DeleteJournal);
            _oneDay = new DelegateCommand<object>(_OneDay);
            _oneWeek = new DelegateCommand<object>(_OneWeek);
            _oneMonth = new DelegateCommand<object>(_OneMonth);
            #endregion

            #region 数据初始化
            StartDate = DateTime.Now.AddDays(-1);
            EndDate = DateTime.Now;
            StartTime = DateTime.Now.ToString("HH:mm");
            EndTime = DateTime.Now.ToString("HH:mm");
            #endregion
        }


        #region 属性绑定:表中数据
        /// <summary>
        /// 当前页内容
        /// </summary>
        public ObservableCollection<Journal> TableData
        {
            get { return _tableData; }
            set
            {
                SetProperty(ref _tableData, value);
            }
        }
        private ObservableCollection<Journal> _tableData;

        /// <summary>
        /// 用户选择行的内容
        /// </summary>
        public Journal SelectedItem
        {
            get 
            { 
                return _selectedItem; 
            }
            set
            {
                _selectedItem = value;
                OnPropertyChanged("SelectedItem");

            }
        }
        private Journal _selectedItem;

        /// <summary>
        /// 当前应该显示的数据，和页面不进行绑定
        /// </summary>
        public DataTable JournalDatas
        {
            get { return _journalDatas; }
            set
            {
                TableData = new ObservableCollection<Journal>();

                for (int i = 0; i < value.Rows.Count; i++)
                {
                    TableData.Add(new Journal()
                    {

                        ID = Convert.ToInt32(value.Rows[i]["序号"]),
                        Content = Convert.ToString((string)value.Rows[i]["内容"]),
                        Type = Convert.ToString((string)value.Rows[i]["类型"]),
                        User = Convert.ToString((string)value.Rows[i]["用户"]),
                        Time = Convert.ToDateTime((DateTime)value.Rows[i]["时间"])
                    });
                }

                SetProperty(ref _journalDatas, value);
            }
        }
        private DataTable _journalDatas;
        #endregion

        #region 属性绑定:页面属性：一共多少页，当前多少页，用户输入多少页
        /// <summary>
        /// 页面总数
        /// </summary>
        public int PageNum
        {
            get { return _pageNum; }
            set { SetProperty(ref _pageNum, value); }
        }
        private int _pageNum;
        /// <summary>
        /// 当前页数
        /// </summary>
        public int CurrentPage
        {
            get { return _currentPage; }
            set { SetProperty(ref _currentPage, value); }
        }
        private int _currentPage;
        /// <summary>
        /// 用户输入页码
        /// </summary>
        public int UserInput
        {
            get { return _userInput; }
            set { SetProperty(ref _userInput, value); }
        }
        private int _userInput;
        #endregion

        #region 属性绑定:右侧按钮以及用户输入时间
        /// <summary>
        /// 只看当前用户
        /// </summary>
        public bool OnlyCurrentUser
        {
            get { return _onlyCurrentUser; }
            set 
            { 
                if (StaticModels.user.User.UserName == "" || StaticModels.user.User.UserName == null)
                {
                    Tips tips = new Tips("当前未登录任何用户");
                    tips.ShowDialog();
                    return;
                }
                SetProperty(ref _onlyCurrentUser, value);
                RefreshWhere();
            }
        }
        private bool _onlyCurrentUser;
        /// <summary>
        /// 打开时间筛选
        /// </summary>
        public bool TimeFilter
        {
            get { return _timeFilter; }
            set 
            { 
                SetProperty(ref _timeFilter, value);
                RefreshWhere();
            }
        }
        private bool _timeFilter;
        /// <summary>
        /// 开始日期
        /// </summary>
        public DateTime StartDate
        {
            get { return _startDate; }
            set 
            { 
                SetProperty(ref _startDate, value);
                RefreshWhere();
            }
        }
        private DateTime _startDate;
        /// <summary>
        /// 开始时间
        /// </summary>
        public string StartTime
        {
            get { return _startTime; }
            set 
            { 
                SetProperty(ref _startTime, value);
                RefreshWhere();
            }
        }
        private string _startTime;
        /// <summary>
        /// 结束日期
        /// </summary>
        public DateTime EndDate
        {
            get { return _endDate; }
            set 
            { 
                SetProperty(ref _endDate, value);
                RefreshWhere();
            }
        }
        private DateTime _endDate;
        /// <summary>
        /// 结束时间
        /// </summary>
        public string EndTime
        {
            get { return _endTime; }
            set 
            { 
                SetProperty(ref _endTime, value);
                RefreshWhere();
            }
        }
        private string _endTime;
        #endregion
        
        #region 事件绑定：页面加载事件
        /// <summary>
        /// 加载
        /// </summary>
        public ICommand LoadedWindow
        {
            get { return _loadedWindow; }
            set
            {
                _loadedWindow = value;
                OnPropertyChanged("LoadedWindow");
            }
        }
        private ICommand _loadedWindow;
        private void _LoadedWindow(object obj)
        {
            if (JournalDatas == null)
            {
                int JournalNum = StaticModels.journal.ReadCount();
                int LastPageNum = JournalNum % StaticModels.staticInfo.config.JournalConfig.OnePageNum;
                PageNum = JournalNum / StaticModels.staticInfo.config.JournalConfig.OnePageNum + 1;
                if (LastPageNum == 0)
                {
                    PageNum--;
                    LastPageNum = StaticModels.staticInfo.config.JournalConfig.OnePageNum;
                }

                CurrentPage = PageNum;

                JournalDatas = StaticModels.journal.ReadJournal((PageNum - 1) * StaticModels.staticInfo.config.JournalConfig.OnePageNum, StaticModels.staticInfo.config.JournalConfig.OnePageNum);


            }


        }
        #endregion

        #region 事件绑定:左下方翻页按钮

        /// <summary>
        /// 打开设置界面
        /// </summary>
        public ICommand OpenSetWindow
        {
            get { return _openSetWindow; }
            set
            {
                _openSetWindow = value;
                OnPropertyChanged("OpenSetWindow");
            }
        }
        private ICommand _openSetWindow;
        private void _OpenSetWindow(object obj)
        {
            StaticModels.journalSet = new Views.Subpage.JournalPage_Son.JournalSet();
            StaticModels.vM_MainWindow.Ambiguity = 5;
            StaticModels.journalSet.ShowDialog();
            StaticModels.vM_MainWindow.Ambiguity = 0;
        }
        /// <summary>
        /// 刷新
        /// </summary>
        public ICommand Refresh
        {
            get { return _refresh; }
            set
            {
                _refresh = value;
                OnPropertyChanged("Refresh");
            }
        }
        private ICommand _refresh;
        private void _Refresh(object obj)
        {
            int JournalNum = StaticModels.journal.ReadCount(Where);
            int LastPageNum = JournalNum % StaticModels.staticInfo.config.JournalConfig.OnePageNum;
            PageNum = JournalNum / StaticModels.staticInfo.config.JournalConfig.OnePageNum + 1;
            if (LastPageNum == 0)
            {
                PageNum--;
                LastPageNum = StaticModels.staticInfo.config.JournalConfig.OnePageNum;
            }

            CurrentPage = PageNum;

            JournalDatas = StaticModels.journal.ReadJournal((PageNum - 1) * StaticModels.staticInfo.config.JournalConfig.OnePageNum, StaticModels.staticInfo.config.JournalConfig.OnePageNum, Where);


        }
        /// <summary>
        /// 导出数据
        /// </summary>
        public ICommand ExportData
        {
            get { return _exportData; }
            set
            {
                _exportData = value;
                OnPropertyChanged("ExportData");
            }
        }
        private ICommand _exportData;
        private void _ExportData(object obj)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            // 设置对话框的标题和默认文件名
            saveFileDialog.Title = "保存日志";
            saveFileDialog.FileName = "日志" + DateTime.Now.ToString("yyyyMMddHHmmss");
            // 设置保存文件的类型
            saveFileDialog.Filter = "word文档|*.docx";

            // 显示对话框
            DialogResult result = saveFileDialog.ShowDialog();

            // 处理用户的选择
            if (result == DialogResult.OK)
            {
                //获取路径
                string filePath = saveFileDialog.FileName;
                //获取需要导出的数据
                DataTable dataTable = StaticModels.journal.ReadJournal(0, StaticModels.journal.ReadCount(Where), Where);
                //输出word
                WordHelper wordHelper = new WordHelper();
                wordHelper.AddDataTable(dataTable);
                wordHelper.SaveWord(filePath);
            }
        }
        /// <summary>
        /// 首页
        /// </summary>
        public ICommand FirstPage
        {
            get { return _firstPage; }
            set
            {
                _firstPage = value;
                OnPropertyChanged("FirstPage");
            }
        }
        private ICommand _firstPage;
        private void _FirstPage(object obj)
        {
            
            int JournalNum = StaticModels.journal.ReadCount(Where);
            int LastPageNum = JournalNum % StaticModels.staticInfo.config.JournalConfig.OnePageNum;
            PageNum = JournalNum / StaticModels.staticInfo.config.JournalConfig.OnePageNum + 1;
            if (LastPageNum == 0)
            {
                PageNum--;
                LastPageNum = StaticModels.staticInfo.config.JournalConfig.OnePageNum;
            }

            CurrentPage = 1;

            JournalDatas = StaticModels.journal.ReadJournal(0, StaticModels.staticInfo.config.JournalConfig.OnePageNum, Where);
        }
        /// <summary>
        /// 上一页
        /// </summary>
        public ICommand PreviousPage
        {
            get { return _previousPage; }
            set
            {
                _previousPage = value;
                OnPropertyChanged("PreviousPage");
            }
        }
        private ICommand _previousPage;
        private void _PreviousPage(object obj)
        {
            int JournalNum = StaticModels.journal.ReadCount(Where);
            int LastPageNum = JournalNum % StaticModels.staticInfo.config.JournalConfig.OnePageNum;
            PageNum = JournalNum / StaticModels.staticInfo.config.JournalConfig.OnePageNum + 1;
            if (LastPageNum == 0)
            {
                PageNum--;
                LastPageNum = StaticModels.staticInfo.config.JournalConfig.OnePageNum;
            }

            if (CurrentPage > 1)
                CurrentPage--;

            JournalDatas = StaticModels.journal.ReadJournal((CurrentPage - 1) * StaticModels.staticInfo.config.JournalConfig.OnePageNum, StaticModels.staticInfo.config.JournalConfig.OnePageNum, Where);


        }
        /// <summary>
        /// 下一页
        /// </summary>
        public ICommand NextPage
        {
            get { return _nextPage; }
            set
            {
                _nextPage = value;
                OnPropertyChanged("NextPage");
            }
        }
        private ICommand _nextPage;
        private void _NextPage(object obj)
        {
            int JournalNum = StaticModels.journal.ReadCount(Where);
            int LastPageNum = JournalNum % StaticModels.staticInfo.config.JournalConfig.OnePageNum;
            PageNum = JournalNum / StaticModels.staticInfo.config.JournalConfig.OnePageNum + 1;
            if (LastPageNum == 0)
            {
                PageNum--;
                LastPageNum = StaticModels.staticInfo.config.JournalConfig.OnePageNum;
            }

            if (CurrentPage < PageNum)
                CurrentPage++;
            JournalDatas = StaticModels.journal.ReadJournal((CurrentPage - 1) * StaticModels.staticInfo.config.JournalConfig.OnePageNum, StaticModels.staticInfo.config.JournalConfig.OnePageNum, Where);

        }

        /// <summary>
        /// 最后一页
        /// </summary>
        public ICommand LastPage
        {
            get { return _lastPage; }
            set
            {
                _lastPage = value;
                OnPropertyChanged("LastPage");
            }
        }
        private ICommand _lastPage;
        private void _LastPage(object obj)
        {
            int JournalNum = StaticModels.journal.ReadCount(Where);
            int LastPageNum = JournalNum % StaticModels.staticInfo.config.JournalConfig.OnePageNum;
            PageNum = JournalNum / StaticModels.staticInfo.config.JournalConfig.OnePageNum + 1;
            if (LastPageNum == 0)
            {
                PageNum--;
                LastPageNum = StaticModels.staticInfo.config.JournalConfig.OnePageNum;
            }

            CurrentPage = PageNum;

            JournalDatas = StaticModels.journal.ReadJournal((PageNum - 1) * StaticModels.staticInfo.config.JournalConfig.OnePageNum, StaticModels.staticInfo.config.JournalConfig.OnePageNum, Where);

        }

        /// <summary>
        /// 前往某一页
        /// </summary>
        public ICommand GoTo
        {
            get { return _goTo; }
            set
            {
                _goTo = value;
                OnPropertyChanged("GoTo");
            }
        }
        private ICommand _goTo;
        private void _GoTo(object obj)
        {
            int JournalNum = StaticModels.journal.ReadCount(Where);
            //纠正用户输入
            if (UserInput > JournalNum)
                UserInput = JournalNum;
            else if (UserInput < 1)
                UserInput = 1;

            int LastPageNum = JournalNum % StaticModels.staticInfo.config.JournalConfig.OnePageNum;
            PageNum = JournalNum / StaticModels.staticInfo.config.JournalConfig.OnePageNum + 1;
            if (LastPageNum == 0)
            {
                PageNum--;
                LastPageNum = StaticModels.staticInfo.config.JournalConfig.OnePageNum;
            }

            CurrentPage = UserInput;

            JournalDatas = StaticModels.journal.ReadJournal((UserInput - 1) * StaticModels.staticInfo.config.JournalConfig.OnePageNum, StaticModels.staticInfo.config.JournalConfig.OnePageNum, Where);

        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string v)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(v));
            //throw new NotImplementedException();
        }


        #endregion

        #region 事件绑定:筛选时间按钮
        /// <summary>
        /// 最新1天
        /// </summary>
        public ICommand OneDay
        {
            get { return _oneDay; }
            set
            {
                _oneDay = value;
                OnPropertyChanged("OneDay");
            }
        }
        private ICommand _oneDay;
        private void _OneDay(object obj)
        {
            StartDate = DateTime.Now.AddDays(-1);
            EndDate = DateTime.Now;
            StartTime = DateTime.Now.ToString("HH:mm");
            EndTime = DateTime.Now.ToString("HH:mm");
        }
        /// <summary>
        /// 最新1周
        /// </summary>
        public ICommand OneWeek
        {
            get { return _oneWeek; }
            set
            {
                _oneWeek = value;
                OnPropertyChanged("OneWeek");
            }
        }
        private ICommand _oneWeek;
        private void _OneWeek(object obj)
        {

            StartDate = DateTime.Now.AddDays(-7);
            EndDate = DateTime.Now;
            StartTime = DateTime.Now.ToString("HH:mm");
            EndTime = DateTime.Now.ToString("HH:mm");
        }
        /// <summary>
        /// 最新1月
        /// </summary>
        public ICommand OneMonth
        {
            get { return _oneMonth; }
            set
            {
                _oneMonth = value;
                OnPropertyChanged("OneMonth");
            }
        }
        private ICommand _oneMonth;
        private void _OneMonth(object obj)
        {

            StartDate = DateTime.Now.AddDays(-30);
            EndDate = DateTime.Now;
            StartTime = DateTime.Now.ToString("HH:mm");
            EndTime = DateTime.Now.ToString("HH:mm");
        }
        #endregion

        #region 事件绑定:表中删除按钮事件
        /// <summary>
        /// 表中删除按钮事件
        /// </summary>
        public ICommand DeleteSingleJournal
        {
            get { return _deleteSingleJournal; }
            set
            {
                _deleteSingleJournal = value;
                OnPropertyChanged("DeleteSingleJournal");
            }
        }
        private ICommand _deleteSingleJournal;
        private void _DeleteSingleJournal(object obj)
        {
            //获取选择行信息
            int SelectdID = SelectedItem.ID;
            string SelectedUser = SelectedItem.User;
            if (StaticModels.user.User.PowerLevel >= 4000)
            {
                //权限不小于4000就允许删除
                ConfirmationWindow confirmationWindow = new ConfirmationWindow("确认删除该条日志?");
                if (confirmationWindow.ShowDialog() == true)
                {
                    StaticModels.journal.DeleteJournal("ID", SelectdID.ToString());
                    RefreshJournal();
                }

            }
            else
            {
                Tips tips = new Tips("只有管理员权限才能删除日志！");
                tips.ShowDialog();
            }

        }
        #endregion

        #region 事件绑定：删除筛选后日志
        /// <summary>
        /// 表中删除按钮事件
        /// </summary>
        public ICommand DeleteJournal
        {
            get { return _deleteJournal; }
            set
            {
                _deleteJournal = value;
                OnPropertyChanged("DeleteJournal");
            }
        }
        private ICommand _deleteJournal;
        private void _DeleteJournal(object obj)
        {
            ConfirmationWindow confirmationWindow = new ConfirmationWindow("是否删除筛选后的日志？注意该行为不可逆！");
            if (confirmationWindow.ShowDialog() == true)
            {
                if (StaticModels.user.User.PowerLevel >= 4000)
                {
                    if (StaticModels.journal.DeleteJournal(Where))
                    {
                        Tips tips = new Tips("删除成功！");
                        tips.ShowDialog();
                    }
                    else
                    {
                        Tips tips = new Tips("未知原因删除失败！");
                        tips.ShowDialog();
                    }

                }
                else
                {
                    Tips tips = new Tips("只有管理员才能批量删除！");
                    tips.ShowDialog();
                }
                //刷新日志
                RefreshJournal();
            }
            
        }
        #endregion

        #region 事件绑定：全能刷新
        public void RefreshJournal()
        {
            int JournalNum = StaticModels.journal.ReadCount(Where);
            int LastPageNum = JournalNum % StaticModels.staticInfo.config.JournalConfig.OnePageNum;
            PageNum = JournalNum / StaticModels.staticInfo.config.JournalConfig.OnePageNum + 1;
            if (LastPageNum == 0)
            {
                PageNum--;
                LastPageNum = StaticModels.staticInfo.config.JournalConfig.OnePageNum;
            }
            if (CurrentPage > PageNum)
            {
                CurrentPage = PageNum;
            }
            JournalDatas = StaticModels.journal.ReadJournal((CurrentPage - 1) * StaticModels.staticInfo.config.JournalConfig.OnePageNum, StaticModels.staticInfo.config.JournalConfig.OnePageNum,Where);

        }
        #endregion

        #region 事件：筛选转where语句逻辑
        string Where;
        void RefreshWhere()
        {
            Where = "";
            string[] screen = new string[] { "","" };
            //如果打开了用户筛选
            if (OnlyCurrentUser)
            {
                screen[0] = "用户 = \"" + StaticModels.user.User.UserName + "\"";
            }
            //如果打开了时间筛选
            
            if (TimeFilter)
            {
                DateTime Start = Convert.ToDateTime(StartDate.ToString("yyyy/MM/dd") + " " + StartTime);
                DateTime End = Convert.ToDateTime(EndDate.ToString("yyyy/MM/dd") + " " + EndTime);
                screen[1] = "时间 between '" + Start.ToString("yyyy-MM-ddTHH:mm:ss") + "' and '" + End.ToString("yyyy-MM-ddTHH:mm:ss") + "'";
            }

            if (screen[0].Length > 0 && screen[1].Length > 0)
            {
                Where = " where ";
                Where += screen[0];
                Where += " and ";
                Where += screen[1];
            }
            else if (screen[0].Length > 0 && screen[1].Length < 1)
            {
                Where = " where ";
                Where += screen[0];
            }
            else if (screen[0].Length < 1 && screen[1].Length > 0)
            {
                Where = " where ";
                Where += screen[1];
            }
        }
        #endregion
    }

    public class Journal
    {
        /// <summary>
        /// ID
        /// </summary>
        public int ID
        {
            get { return _iD; }
            set 
            { 
                _iD = value;
            }
        }
        private int _iD;

        /// <summary>
        /// 日志内容
        /// </summary>
        public string Content
        {
            get 
            { 
                
                return _content; 
            }
            set 
            { 
                _content = value; 
            }
        }
        private string _content;

        /// <summary>
        /// 类型
        /// </summary>
        public string Type
        {
            get { return _type; }
            set { _type = value; }
        }
        private string _type;

        /// <summary>
        /// 用户
        /// </summary>
        public string User
        {
            get { return _user; }
            set { _user = value; }
        }
        private string _user;

        /// <summary>
        /// 时间
        /// </summary>
        public DateTime Time
        {
            get { return _time; }
            set { _time = value; }
        }
        private DateTime _time;
    }

    
}
